const fs = require('fs');
const path = require('path');

// Expect address output file produced after deployment
// Usage: node scripts/export-address.js <address>
const address = process.argv[2];
if(!address){
  console.error('Usage: node scripts/export-address.js <launchpadAddress>');
  process.exit(1);
}

// __dirname => smart-contracts/xlayer-contracts/scripts
// project root = ../../../
const root = path.join(__dirname, '../../../');
const frontendEnv = path.join(root, 'frontend/.env.local');
const backendEnv = path.join(root, 'backend/.env');

function upsertEnv(file, key, value){
  let content = '';
  if(fs.existsSync(file)) content = fs.readFileSync(file,'utf8');
  const lines = content.split(/\n/).filter(l=>l.trim().length>0 && !l.startsWith('#') && !l.startsWith(key+'='));
  lines.push(`${key}=${value}`);
  fs.writeFileSync(file, lines.join('\n')+'\n');
  console.log('Updated', file, '=>', key, '=', value);
}

upsertEnv(frontendEnv,'NEXT_PUBLIC_XLAYER_LAUNCHPAD_ADDRESS',address);
upsertEnv(backendEnv,'XLAYER_LAUNCHPAD_ADDRESS',address);
